package com.yami.shop.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.merchanttransfer.TransferCreateRequest;
import com.github.binarywang.wxpay.bean.merchanttransfer.TransferCreateResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.yami.shop.bean.event.EnterprisePayFailEvent;
import com.yami.shop.bean.event.EnterprisePaySuccessEvent;
import com.yami.shop.bean.model.EnterprisePay;
import com.yami.shop.common.bean.WxApp;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.config.HnaPayConfig;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.config.WxConfig;
import com.yami.shop.dao.EnterprisePayMapper;
import com.yami.shop.service.EnterprisePayService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * @author
 * @date 2019-10-15 16:44:50
 */
@Slf4j
@Service
@AllArgsConstructor
public class EnterprisePayServiceImpl extends ServiceImpl<EnterprisePayMapper, EnterprisePay> implements EnterprisePayService {

    private final EnterprisePayMapper enterprisePayMapper;

    private final ApplicationContext applicationContext;

    private static final String CLIENT_IP = "127.0.0.1";

    private final WxConfig wxConfig;

    private final HnaPayConfig hnaPayConfig;

    private final ShopConfig shopConfig;

    private final Snowflake snowflake;

    @Override
    public List<EnterprisePay> listApplyEnterprisePay() {
        return enterprisePayMapper.listApplyEnterprisePay();
    }

    @Override
    public List<EnterprisePay> listEnterprisePay() {
        return enterprisePayMapper.listEnterprisePay();
    }

    @Override
    public void sendEnterprisePay(List<EnterprisePay> enterprisePayList) {
        if (CollectionUtils.isEmpty(enterprisePayList)) {
            return;
        }
        String outBatchNo = snowflake.nextIdStr();
        TransferCreateRequest transferCreateRequest = new TransferCreateRequest();
        WxApp wxApp = shopConfig.getWxApp();
        transferCreateRequest.setAppid(wxApp.getAppId());
        transferCreateRequest.setOutBatchNo(outBatchNo);
        transferCreateRequest.setBatchName("NO_CHECK");
        transferCreateRequest.setBatchRemark("yami.cash.grant");
        List<TransferCreateRequest.TransferDetailList> transferDetailList = new ArrayList<>();
        int totalAmount = 0;
        for (EnterprisePay enterprisePay : enterprisePayList) {
            TransferCreateRequest.TransferDetailList transferDetail = new TransferCreateRequest.TransferDetailList();
            transferDetail.setOpenid(enterprisePay.getOpenId());
            transferDetail.setOutDetailNo(String.valueOf(enterprisePay.getEntPayOrderNo()));
            int amout = (int) Arith.mul(enterprisePay.getAmount(), 100.0);
            transferDetail.setTransferAmount(amout);
            transferDetailList.add(transferDetail);
            totalAmount += amout;
        }
        transferCreateRequest.setTotalAmount(totalAmount);
        transferCreateRequest.setTotalNum(enterprisePayList.size());
        transferCreateRequest.setTransferDetailList(transferDetailList);
        try {
            TransferCreateResult transfer = wxConfig.getMerchantTransferService().createTransfer(transferCreateRequest);
            enterprisePayList.forEach(enterprisePay -> {
                enterprisePay.setOutBatchNo(transfer.getOutBatchNo());
                //enterprisePay.setBatchId(transfer.getBatchId());
            });
            updateBatch(enterprisePayList);
        } catch (WxPayException wxPayException) {
            wxPayException.printStackTrace();
        }
    }

    @Override
    public void sendEnterpriseXsPay(List<EnterprisePay> enterprisePayList) {
        if (CollectionUtils.isEmpty(enterprisePayList)) {
            return;
        }
        String outBatchNo = snowflake.nextIdStr();
    }


    @Override
    public void sendEnterprisePay(EnterprisePay enterprisePay) {
        if (Objects.isNull(enterprisePay)) {
            return;
        }
        TransferCreateRequest transferCreateRequest = new TransferCreateRequest();
        WxApp wxApp = shopConfig.getWxApp();
        transferCreateRequest.setAppid(wxApp.getAppId());
        transferCreateRequest.setOutBatchNo(enterprisePay.getOutBatchNo());
        transferCreateRequest.setBatchName("NO_CHECK");
        transferCreateRequest.setBatchRemark("yami.cash.grant");
        List<TransferCreateRequest.TransferDetailList> transferDetailList = new ArrayList<>();
        TransferCreateRequest.TransferDetailList transferDetail = new TransferCreateRequest.TransferDetailList();
        transferDetail.setOpenid(enterprisePay.getOpenId());
        transferDetail.setOutDetailNo(String.valueOf(enterprisePay.getEntPayOrderNo()));
        int amout = (int) Arith.mul(enterprisePay.getAmount(), 100.0);
        transferDetail.setTransferAmount(amout);
        transferDetailList.add(transferDetail);
        transferCreateRequest.setTotalAmount(amout);
        transferCreateRequest.setTotalNum(1);
        transferCreateRequest.setTransferDetailList(transferDetailList);
        try {
            wxConfig.getMerchantTransferService().createTransfer(transferCreateRequest);
        } catch (WxPayException wxPayException) {
            wxPayException.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccess(EnterprisePay enterprisePay) {
        //更新商家转账信息
        if (enterprisePayMapper.paySuccess(enterprisePay.getEntPayOrderNo(), enterprisePay.getVersion()) != 1) {
            // 更新余额记录失败，请稍后再试
            throw new YamiShopBindException("yami.shop.update.balance");
        }
        // 推送支付成功事件
        applicationContext.publishEvent(new EnterprisePaySuccessEvent(enterprisePay));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payFailed(EnterprisePay enterprisePay) {
        //更新商家转账信息
        if (enterprisePayMapper.payFailed(enterprisePay.getEntPayOrderNo(), enterprisePay.getVersion()) != 1) {
            // 更新余额记录失败，请稍后再试
            throw new YamiShopBindException("yami.shop.update.balance");
        }
        // 推送支付失败事件
        applicationContext.publishEvent(new EnterprisePayFailEvent(enterprisePay));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(List<EnterprisePay> enterprisePayList) {
        enterprisePayMapper.updateBatch(enterprisePayList);
    }
}
